package org.biubiu0002.baiblog.im.concurrent;

import com.google.common.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Author: biubiu0002
 * @Date: 2022/8/30 23:31
 **/
@Slf4j
public class CallbackTaskScheduler {

    static ListeningExecutorService gPoll = null;

    static {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("MyThread-%d").build();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1000),
                threadFactory, new ThreadPoolExecutor.AbortPolicy()
        );
        gPoll = MoreExecutors.listeningDecorator(executor);
    }

    public static <R> void add(CallbackTask<R> executeTask){
        ListenableFuture<R> future = gPoll.submit(new Callable<R>() {
            @Override
            public R call() throws Exception {
                return executeTask.execute();
            }
        });

        Futures.addCallback(future, new FutureCallback<R>() {
            @Override
            public void onSuccess(R r) {
                executeTask.onBack(r);
            }

            @Override
            public void onFailure(Throwable throwable) {
                executeTask.onException(throwable);
            }
        },gPoll);
    }

}
